// pages/addGood/addGood.js
import {
  addMerchant,
  getToken,
  productDetail,
  infoGoodsDetail,
  saveEdit,
  delGoods,
  // addEditProduct,
  productDetailNew,
  currencyConversion,
  addProduct,
  isNetwork
} from '../../api.js'
let app = getApp();
Page({
  data: {
    background:false,
    proids:"",
    inner:"",
    allnet:true,
    a:false,
    b:true,
    ids:2,
    is_iPhoneX:false,
    // 是否上架小程序
    small:true,
    isshow:true,
    id:-1,
    maintenance:"2",
    items:[
      {
        name:"有",
        checked:true
      },
      {
        name:"无",
        checked:false
      }
    ],
    i:0,
    color:"",
    disabled: false, //查看商品详情
    isEdit: false, //编辑商品
    type: 0,
    isChecked: 0, //商品类型选择
    isChecked2: 2, //商品保养选择
    isChecked3: 2, //上下架选择
    isChecked4: 2, //入库同步选择
    isChecked5: 2, //入库同步选择
    showCommQuality: false,
    showLibraryAge: false,
    showTradePrice: false,
    liemu1: false,
    show1: false,
    show2: false,
    show3: false,
    show4: false,
    liemu2: false,
    liemu3: false,
    liemu4: false,
    sourceFocus: false,
    showImages: [], //显示图片
    productFineness: [], //商品成色说明
    perchaseSource: [], //商品采购类别
    warehouseCondition: [], //商品库存状态
    pro_index: -1,
    war_index: -1,
    per_index: -1,
    sourceFocus: false, //商品来源自动聚焦
    addEdit: {
      id:"",
      product_condition:"",
      image: [],
      product_cate: 0, //商品类型 0 二手 1 全新
      finess_value: '', //商品成色  
      product_condition: '', //商品成色
      is_shelf: '', //库存状态
      wc_value: '', //库存状态（文字）
      procurement_value: '', //采购类别
      procurement_status: '', //采购类别
      goodsLeibie: '', //商品类别
      cag_title: '',
      type_title: '',
      brand_title: '',
      systematics_title: '',
      category_id: '', //大类目
      type_id: '', //小类目
      brand_id: '', //品牌
      systematics_id: '', //系列
      product_sn: '', //商品货号
      product_name: '', //商品名称
      product_code: '', //商品编码
      maintenance: 2, //商品保养情况
      store_name: '', //所在门店
      store_id: '', //所在门店 
      coordinate: '', //商品坐标
      library_age: '', //预警库龄
      remark: '', //备注
      cost_price: '', //采购价
      additional: '', //额外费用
      product_source: '', //商品来源
      source_phone: '', //商品来源电话
      source_name: '', //商品来源姓名
      staff_name: '', //采购员
      staff_id: '', //采购员    
      price: '', //销售价
      peer_price: '', //同行价
      is_onsale: 2, //是否上架 2 下 1 上
      is_network: 1, //是否入全网 2否 1 是
      stock: 1, //库存数量*（定值）
      activity_price: '', //活动价
      market_price: '', //市场价
      product_service: ['专业鉴定', "非质量问题不退换", "售后保障"], //商品服务
      group_people: '男女通用', //适用人群
      color: '', //颜色
      material: '', //材质
      size: '', //配饰尺码
      product_package: [], //包装清单
      watchshell_material: [], //表壳材质
      watchband_material: '', //表带材质
      mechanism: '手动机械', //机芯类型
      diameter: '', //表直径
      fastener_type: '', //表扣类型
      waterproof: '', //防水
      guarantee: '', //保修功能
      producer: '', //产地
      fineness_description: '', //成色描述
      synopsis: '', //小编推荐
      product_specification: { //产品规格
        longness: '', //长
        width: '', //宽
        height: '', //高
        size: '', //尺寸
        other: '', //其他
      },
      inside_structure: '', //内里结构
      brand_other:'',//自定义品牌
      systematics_other:'',//自定义品类
      peer_price_amount:'',
      peer_price_currency:'JPY',
      is_bid:0,//是否是拍卖
      bid_price:'',//拍卖底价
      is_bid_sold:0,//是否成交
      bid_sold_price:'',//拍卖成交价格
      bid_phone:'',//成交者手机号
      is_keep:0,//是否保留
      keep_price:'',//保留价
      is_unsold:0,//是否流拍
      unsold_price:'',//流拍价
    },
    goodsCate: [],
    secondCate: [],
    thirdCate: [],
    xiLie: [],
    index: -1,
    index2: -1,
    index3: -1,
    index4: -1,
    pIndex: 0, //商品传的index
    groupPeopleRadio: '男女通用',
    mechanism_Radio: '手动机械',
    token_pic: '',
    pic_lis: [],
    key_pic: '',
    qiniu_key: [],
    count: 9,
    detailedList: [{
        name: '肩带',
        state: 0
      },
      {
        name: '钥匙',
        state: 0
      },
      {
        name: '锁',
        state: 0
      },
      {
        name: '盒子',
        state: 0
      },
      {
        name: '防尘袋',
        state: 0
      },
      {
        name: '身份卡',
        state: 0
      },
      {
        name: '发票',
        state: 0
      },
      {
        name: '说明书',
        state: 0
      },
      {
        name: '保卡',
        state: 0
      },
      {
        name: '国检证书',
        state: 0
      },
      {
        name: '纸卡',
        state: 0
      },
      {
        name: '防尘布',
        state: 0
      },
      {
        name: '纸片',
        state: 0
      },
      {
        name: '质保卡',
        state: 0
      },
      {
        name: '内袋',
        state: 0
      },
      {
        name: '吊牌',
        state: 0
      },
      {
        name: '表节',
        state: 0
      },
      {
        name: '配钉',
        state: 0
      },
      {
        name: '配皮',
        state: 0
      },
      {
        name: '手提袋',
        state: 0
      },
      {
        name: '刷卡单',
        state: 0
      },
      {
        name: '小票',
        state: 0
      },
      {
        name: '挂件',
        state: 0
      },
      {
        name: '螺丝刀',
        state: 0
      },
      {
        name: '手柄',
        state: 0
      },
      {
        name: '替换袋',
        state: 0
      },
      {
        name: '皮绳',
        state: 0
      },
      {
        name: '皮条',
        state: 0
      },
      {
        name: '羊毛毡',
        state: 0
      },
      {
        name: '丝带',
        state: 0
      },
      {
        name: '镜子',
        state: 0
      },
      {
        name: '扣子',
        state: 0
      },
      {
        name: '雨衣',
        state: 0
      },
    ],
    product_inp: '', //包装清单input
    biaoke_inp: '', //表壳
    CaseMaterial: [{
      name: '精钢',
      state: 0
    }, {
      name: '玫瑰金',
      state: 0
    }, {
      name: '黄金',
      state: 0
    }, {
      name: '白金',
      state: 0
    }, {
      name: '镶钻',
      state: 0
    }, {
      name: '后镶钻',
      state: 0
    }, {
      name: '黑色高科技精密陶瓷',
      state: 0
    }, {
      name: '钛金属',
      state: 0
    }],
    BandMaterial: [{
      name: '精钢',
      state: 0
    }, {
      name: '玫瑰金',
      state: 0
    }, {
      name: '黄金',
      state: 0
    }, {
      name: '白金',
      state: 0
    }, {
      name: '镶钻',
      state: 0
    }, {
      name: '后镶钻',
      state: 0
    }, {
      name: '牛皮',
      state: 0
    }, {
      name: '鳄鱼皮',
      state: 0
    }, {
      name: '橡胶',
      state: 0
    }, {
      name: '后配',
      state: 0
    }, {
      name: '帆布',
      state: 0
    }],
    BandMaterial_inp: '',
    business_id: '',
    fuc: '',
    qiniuImg: [],
    options: '',
    currencyList:[],
    currency_index:-1,
    currency_num:'',
    guojia:'',
    bid_radio_type:0,
    none:false,
    small:"是"
  },
  //商品描述
  //商品入出全网
  isNetwork(e) {
    let id = this.data.proids;
    let is_network = (this.data.addEdit.is_network == 2 ? 1 : 2);
    this.isNetwork_fun(id, is_network)
  },
  //商品入出全网(封装)
  isNetwork_fun(id, is_network) {
    isNetwork({
      token: app.globalData.token,
      id: id,
      is_network: is_network
    }).then(res => {
      if (res.data.code == 666) {
        this.setData({
          "addEdit.is_network": is_network
          })
        this.data.addEdit.is_network == 2 ? this.setData({
          inner: "加入货源",
          background:true
        }) : this.setData({
          inner: "移出货源",
          background:false
        })
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        })
      } else if (res.data.code == 111111) {
        wx.showToast({
          title: '登录失效，请重新登录',
          icon: 'none',
        })
        setTimeout(function () {
          wx.reLaunch({
            url: '/pages/user/login/login',
          })
        }, 1500)
      } else {
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        })
      }

    })
  },
  // 入全网选择
  gouxuan(e){
    console.log(e)
    e.currentTarget.dataset.id == 2 ? this.setData({
      a:true,
      b:false,
      "addEdit.is_network":2
    }) : this.setData({
      a:false,
      b:true,
        "addEdit.is_network": 1
    })
  },
  //包装清单
  radioChange(e){
    console.log(e)
    return e.detail.value == "无" ? this.setData({
      none:true
    }) : this.setData({
        none:false
    })
  },
  showtime(){
    this.setData({
      isshow:false
    })
  },
  bt(){
    this.setData({
      isshow:true
    })
  },

  onLoad: function(options) { 
    options.id ? this.setData({
      allnet:false,
      proids: options.id,
      "addEdit.id":options.id
    }) : ""
    app.globalData.is_iPhoneX ? this.setData({
      is_iPhoneX:true
    }) : ""
    this.setData({
      current_page: options.current_page ? options.current_page : "",
      pIndex: options.index ? options.index : 0,
      options: options,
      guojia: app.globalData.guojia
    })
    let _this = this;
    currencyConversion({}).then(res => {
      _this.setData({
        currencyList: res.data.data
      })
      for (var i = 0; i < res.data.data.length; i++) {
        if (res.data.data[i].name == 'JPY') {
          _this.setData({
            currency_num: res.data.data[i].value
          })
        }
      }
    })
    if (options.id) {
      if (options.fuc) {
        _this.setData({
          fuc: 0
        })
        wx.setNavigationBarTitle({
          title: '商品详情',
        })
        _this.setData({
          disabled: true
        })
      } else {
        _this.setData({
          fuc: 1
        })
        wx.setNavigationBarTitle({
          title: '编辑商品',
        })
      }
      wx.showLoading({
        title: '加载中',
      })
      if (options.fuc) {
        infoGoodsDetail({
          token: app.globalData.token,
          id: options.id
        }).then(res => {
          if (res.data.code == 666) {
            var data = res.data.data;
            var Images = [];
            data.image.forEach(item => {
              Images.push(item.pic_url);
            })
            var bid_radio_type = 0
            if(data.is_bid_sold){
              bid_radio_type = 1
            }else if(data.is_keep){
              bid_radio_type = 2
            }else if(data.is_unsold){
              bid_radio_type = 3
            }
            _this.setData({
              addEdit: data,
              isChecked: data.product_cate,
              isChecked2: data.maintenance,
              isChecked3: data.is_onsale,
              isChecked4: data.is_network,
              isChecked5:data.is_bid,
              isEdit: true,
              showImages: Images,
              'addEdit.stock': 1,
              'addEdit.page': 1,
              bid_radio_type: bid_radio_type
            })
            addEdit.is_network == 2 ? this.setData({
                inner:"加入货源"
            }) : this.setData({
                inner:"移出货源"
            })
          } else if (res.data.code == 111111) {
            wx.showToast({
              title: '登录失效，请重新登录',
              icon: 'none',
            })
            setTimeout(function() {
              wx.reLaunch({
                url: '/pages/user/login/login',
              })
            }, 1500)
          } else {
            wx.showToast({
              title: res.data.msg,
              icon: 'none'
            })
          }
          wx.hideLoading();
        })
      } else {
        productDetailNew({
          token: app.globalData.token,
          id: options.id
        }).then(res => {
          if (res.data.code == 666) {
            this.setData({
              maintenance: res.data.data.maintenance
            })
            var id = res.data.data.product_fineness_id
            console.log(id)
            id ? this.setData({
              id:id == 7 ? 0 : id
            }) : ""
            for (let i in this.data.productFineness){
              id == this.data.productFineness[i].id
              id = i;
              break
            }
            res.data.data.is_network == 2 ? this.setData({
              inner:"加入货源",
              background:true
            }) : this.setData({
              inner:"移出货源",
              background:false
            })
            var data = res.data.data;
            var Images = []
            for (var i = 0; i < data.image.length; i++) {
              Images.push(data.image[i].pic_url)
            }
            if (res.data.data.category_id == 2) {
              var watchshell_material_lis = res.data.data.watchshell_material
              for (var j = 0; j < watchshell_material_lis.length; j++) {
                for (var a = 0; a < _this.data.CaseMaterial.length; a++) {
                  if (watchshell_material_lis[j].watchshell_material == _this.data.CaseMaterial[a].name) {
                    _this.data.CaseMaterial[a].state = 1
                    _this.data.CaseMaterial[a].id = watchshell_material_lis[j].id
                  }
                }
              }

              var watchband_material_lis = res.data.data.watchband_material
              for (var b = 0; b < watchband_material_lis.length; b++) {
                for (var c = 0; c < _this.data.BandMaterial.length; c++) {
                  if (watchband_material_lis[b].watchband_material == _this.data.BandMaterial[c].name) {
                    _this.data.BandMaterial[c].state = 1
                    _this.data.BandMaterial[c].id = watchband_material_lis[b].id
                  }
                }
              }
            }
            var product_package_lis = res.data.data.product_package
            for (var b = 0; b < product_package_lis.length; b++) {
              for (var c = 0; c < _this.data.detailedList.length; c++) {
                if (product_package_lis[b].package_name == _this.data.detailedList[c].name) {
                  _this.data.detailedList[c].state = 1
                  _this.data.detailedList[c].id = product_package_lis[b].id
                }
              }
            }
            for (var i = 0; i < _this.data.currencyList; i++) {
              if (_this.data.currencyList[i].name == data.peer_price_currency) {
                _this.setData({
                  currency_num: _this.data.currencyList[i].value,
                  currency_index:i
                })
              }
            }
            var bid_radio_type = 0
            if (data.is_bid_sold) {
              bid_radio_type = 1
            } else if (data.is_keep) {
              bid_radio_type = 2
            } else if (data.is_unsold) {
              bid_radio_type = 3
            }
            _this.setData({
              addEdit: res.data.data,
              showImages: Images,
              pro_index: res.data.data.product_condition - 1,
              war_index: res.data.data.is_shelf - 1,
              per_index: res.data.data.procurement_status - 1,
              isEdit: true,
              groupPeopleRadio: res.data.data.group_people,
              // mechanism_Radio: res.data.data.mechanism,
              CaseMaterial: _this.data.CaseMaterial,
              BandMaterial: _this.data.BandMaterial,
              detailedList: _this.data.detailedList,
              isChecked3: data.is_onsale,
              isChecked4: data.is_network,
              isChecked: data.product_cate,
              isChecked5: data.is_bid,
              bid_radio_type: bid_radio_type
            })
          } else if (res.data.code == 111111) {
            wx.showToast({
              title: '登录失效，请重新登录',
              icon: 'none',
            })
            setTimeout(function() {
              wx.reLaunch({
                url: '/pages/user/login/login',
              })
            }, 1500)
          } else {
            wx.showToast({
              title: res.data.msg,
              icon: 'none'
            })
          }
          wx.hideLoading();
        })
      }
    }
    addMerchant({
      token: app.globalData.token
    }).then(res => {
      _this.setData({
        productFineness: res.data.data.product_fineness,
        perchaseSource: res.data.data.perchase_source,
        warehouseCondition: res.data.data.warehouse_condition,
        business_id: res.data.data.business_id
      })
      console.log(this.data.productFineness)
    })    
  },

  //选择图片
  addImg: function() {
    var that = this
    wx.chooseImage({
      count: that.data.count,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        console.log(res)
        var tempFilePaths = res.tempFilePaths;
        var showImages = that.data.showImages.concat(tempFilePaths)
        if (15 - tempFilePaths.length > 9) {
          that.setData({
            count: 9
          })
        } else {
          that.setData({
            count: 15 - tempFilePaths.length
          })
        }
        that.setData({
          showImages: showImages,
        })
        getToken().then(res => {
          that.setData({
            token_pic: res.data.data.token,
          })
          that.uplod(tempFilePaths, 20)
        })
      }
    })
  },
  //图片上传到七牛
  uplod: function(obj, num) {
    var that = this
    var showImages = that.data.showImages
    for (var i = 0; i < obj.length; i++) {
      var timestamp = Date.parse(new Date()) + [i]
      var type = obj[i].substring(obj[i].lastIndexOf("."), obj[i].length);
      var keyy = timestamp + type
      wx.uploadFile({
        url: 'https://upload.qiniup.com',
        filePath: obj[i],
        name: 'file', //文件的key 
        header: {
          "Content-Type": "multipart/form-data"
        },
        formData: {
          token: that.data.token_pic,
          key: keyy
        }, //传递参数
        success: function(res) {
          var data = JSON.parse(res.data)
          var singleImg = {};
          if (that.data.isEdit) {
            singleImg.id = '';
          }
          if (num != 20) {
            that.data.addEdit.image[num].pic_url = data.key
            that.data.addEdit.image[num].id = that.data.showImages[num].id
          } else {
            var image = that.data.addEdit.image;
            var min;
            singleImg.pic_url = data.key
            image.push(singleImg)
            for (var i = 0; i < image.length; i++) {
              for (var j = i; j < image.length; j++) {
                if (parseInt(image[i].pic_url) > parseInt(image[j].pic_url)) {
                  min = image[j].pic_url;
                  image[j].pic_url = image[i].pic_url;
                  image[i].pic_url = min;
                }
              }
            }
            console.log(image)
          }
          that.setData({
            addEdit: that.data.addEdit
          })
        }
      })
    }
  },
  //替换img
  changeImg: function(e) {
    console.log(e.currentTarget.dataset.key)
    var inde = e.currentTarget.dataset.key
    var that = this
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        var tempFilePaths = res.tempFilePaths;
        var showImages = that.data.showImages.splice(inde, 1, tempFilePaths[0])
        that.setData({
          showImages: that.data.showImages
        })
        console.log(that.data.showImages)
        getToken().then(res => {
          that.setData({
            token_pic: res.data.data.token,
          })
          that.uplod(tempFilePaths, inde)
        })
      }
    })
  },
  // 成色
  toCommQuality(e) {
    this.setData({
      id: e.currentTarget.dataset.index,
      "addEdit.product_condition": this.data.productFineness[e.currentTarget.dataset.index].id,
      "addEdit.fineness_value": this.data.productFineness[e.currentTarget.dataset.index].value,
      "addEdit.product_condition": this.data.productFineness[e.currentTarget.dataset.index].id,
      "addEdit.finess_value":e.target.dataset.value
    
    })
   
  },
  //库存状态
  toProductStatus(e) {
    this.data.addEdit.wc_value = this.data.warehouseCondition[e.detail.value].value
    this.data.addEdit.is_shelf = this.data.warehouseCondition[e.detail.value].id
    this.setData({
      war_index: e.detail.value
    })
  },
  // 采购类别
  toPurchaseCate(e) {
    this.data.addEdit.procurement_value = this.data.perchaseSource[e.detail.value].value
    this.data.addEdit.procurement_status = this.data.perchaseSource[e.detail.value].id
    this.setData({
      per_index: e.detail.value
    })
    if (this.data.fuc == 0) {
      this.productSn()
    }
  },
  //商品类别
  toGoodsCate() {
    var that = this
    var toGoodsCate_lis = {
      cag_title: that.data.addEdit.cag_title,
      category_id: that.data.addEdit.category_id,
      type_title: that.data.addEdit.type_title,
      type_id: that.data.addEdit.type_id,
    }
    wx.navigateTo({
      url: '/pages/addGood/goodsCate/goodsCate?lis=' + JSON.stringify(toGoodsCate_lis),
    })
  },
  toGoodsBrand(e) {
    var that = this
    var toGoodsCate_lis = {
      brand_title: that.data.addEdit.brand_title,
      brand_id: that.data.addEdit.brand_id,
      systematics_title: that.data.addEdit.systematics_title,
      systematics_id: that.data.addEdit.systematics_id,
      brand_other: that.data.addEdit.brand_other,
      systematics_other: that.data.addEdit.systematics_other,
    }
    wx.navigateTo({
      url: '/pages/addGood/goodsBrand/goodsBrand?lis=' + JSON.stringify(toGoodsCate_lis),
    })
    console.log(e)
  },
  //商品货号
  productSn() {
    var a = String(new Date().getTime())
    var that = this
    if (that.data.addEdit.category_id) {
      var leibie = ''
      var pinpai = ''
      if (that.data.addEdit.brand_id) {
        leibie = that.data.addEdit.brand_id
      }
      if (that.data.addEdit.brand_title){
        pinpai = that.data.addEdit.brand_title.substring(0, 2)
      }
      console.log(that.data.addEdit.brand_id)
     
      console.log(a)
      var num = that.data.business_id + leibie + pinpai + a.substring(8)
      that.setData({
        'addEdit.product_sn': num
      })
    }
  },
  // 是否上架
  checkboxOnsale(e) {
    console.log('eee', e)
    if (e.detail.value.length > 0) {
      this.setData({
        'addEdit.is_onsale': Number(e.detail.value[0]),
        isChecked3: 1
      })
    } else {
      this.setData({
        'addEdit.is_onsale': 2,
        isChecked3: 2
      })
    }
  },
  //是否入全网
  checkboxNetwork(e) {
    if (e.detail.value.length > 0) {
      this.setData({
        'addEdit.is_network': 1,
        isChecked4: 1
      })
    } else {
      this.setData({
        'addEdit.is_network': 2,
        isChecked4: 0
      })
    }
    console.log(e)
    console.log('入全网', this.data.addEdit.is_network)
  },
  //是否是拍卖
  checkauction(e){
    if (e.detail.value.length > 0) {
      this.setData({
        'addEdit.is_bid': 1,
        isChecked5: 1
      })
    } else {
      this.setData({
        'addEdit.is_bid': 0,
        isChecked5: 0
      })
    }
  },
  //所在门店
  toInStore() {
    wx.navigateTo({
      url: 'inStore/inStore',
    })
  },
  //采购员
  toBuyer() {
    let store_id = this.data.addEdit.store_id ? this.data.addEdit.store_id : '';
    wx.navigateTo({
      url: 'buyer/buyer?store_id=' + store_id,
    })
  },
  //商品类型选择
  // typeSelected(e) {
  //   this.setData({
  //     'addEdit.product_cate': Number(e.detail.value),
  //     isChecked: Number(e.detail.value)
  //   })
  // },

  //商品货号
  bindProductSn(e) {
    if (/^([a-zA-Z0-9])+$/.test(e.detail.value)) {
      this.setData({
        'addEdit.product_sn': e.detail.value
      })
    } else {
      wx.showToast({
        title: '商品货号请填写字母和数字',
        icon: 'none',
      })
      this.setData({
        'addEdit.product_sn': e.detail.value.substring(0, e.detail.value.length - 1)
      })
      return
    }
  },

  //基础信息复制
  handleInfoCopy(e) {
    let content = e.target.dataset.content
    wx.setClipboardData({
      data: content,
      success() {
        wx.showToast({
          title: '复制成功',
        })
      }
    })
    console.log('content', content);
  },

  //商品名称
  bindProductName(e) {
    this.setData({
      'addEdit.product_name': e.detail.value
    })
  },
  //商品自带编码
  bindProductCode(e) {
    this.setData({
      'addEdit.product_code': e.detail.value
    })
  },
  //存放坐标
  bindCoordinate(e) {
    this.setData({
      'addEdit.coordinate': e.detail.value
    })
  },
  //预警库龄
  bindLibraryAge(e) {
    this.setData({
      'addEdit.library_age': e.detail.value
    })
  },
  //商品描述
  bindSynopsis(e) {
    this.setData({
      'addEdit.synopsis': e.detail.value
    })
  },
  //备注
  bindRemark(e) {
    this.setData({
      'addEdit.remark': e.detail.value
    })
  },
  //商品采购价
  bindCostPrice(e) {
    if (/^(\d?)+(\.\d{0,2})?$/.test(e.detail.value)) {
      this.setData({
        'addEdit.cost_price': e.detail.value
      })
    } else {
      wx.showToast({
        title: '商品采购价请填写数字',
        icon: 'none',
      })
      this.setData({
        'addEdit.cost_price': e.detail.value.substring(0, e.detail.value.length - 1)
      })
      return
    }

  },
  //额外费用
  bindAdditional(e) {
    if (/^(\d?)+(\.\d{0,2})?$/.test(e.detail.value)) {
      this.setData({
        'addEdit.additional': e.detail.value
      })
    } else {
      wx.showToast({
        title: '额外费用请填写数字',
        icon: 'none',
      })
      this.setData({
        'addEdit.additional': e.detail.value.substring(0, e.detail.value.length - 1)
      })
      return
    }
  },
  //商品来源
  bindProducSource(e) {
    this.setData({
      'addEdit.product_source': e.detail.value
    })
  },
  //销售价
  bindPrice(e) {
    if (/^(\d?)+(\.\d{0,2})?$/.test(e.detail.value)) {
      this.setData({
        'addEdit.price': e.detail.value
      })
    } else {
      wx.showToast({
        title: '销售价请填写数字',
        icon: 'none',
      })
      this.setData({
        'addEdit.price': e.detail.value.substring(0, e.detail.value.length - 1)
      })
      return
    }
  },
  //同行价
  bindPeerPrice(e) {
    var that = this
    if (/^(\d?)+(\.\d{0,2})?$/.test(e.detail.value)) {
      var bei = ''
      if (that.data.options.id) {
        for (var i = 0; i < that.data.currencyList.length; i++) {
          if (that.data.currencyList[i].name == that.data.addEdit.peer_price_currency) {
            bei = that.data.currencyList[i].value
          }
        }
      } else {
        bei = that.data.currency_num
    }
      this.setData({
        'addEdit.peer_price': e.detail.value,
        'addEdit.peer_price_amount': e.detail.value * bei
      })
    } else {
      wx.showToast({
        title: '同行价请填写数字',
        icon: 'none',
      })
      this.setData({
        'addEdit.peer_price': e.detail.value.substring(0, e.detail.value.length - 1)
      })
      return
    }
  },
  bindPeerPricecurrency(e){
    var that = this
    if (/^(\d?)+(\.\d{0,2})?$/.test(e.detail.value)) {
      var bei = ''
      if (that.data.options.id) {
        for (var i = 0; i < that.data.currencyList.length; i++) {
          if (that.data.currencyList[i].name == that.data.addEdit.peer_price_currency) {
            bei = that.data.currencyList[i].value
          }
        }
      } else {
        bei = that.data.currency_num
      }
      this.setData({
        'addEdit.peer_price': e.detail.value / bei,
        'addEdit.peer_price_amount': e.detail.value
      })
    } else {
      wx.showToast({
        title: '同行价请填写数字',
        icon: 'none',
      })
      this.setData({
        'addEdit.peer_price_amount': e.detail.value.substring(0, e.detail.value.length - 1)
      })
      return
    }
  },
  //活动价
  activityPrice(e) {
    if (/^(\d?)+(\.\d{0,2})?$/.test(e.detail.value)) {
      this.setData({
        'addEdit.activity_price': e.detail.value
      })
    } else {
      wx.showToast({
        title: '活动价请填写数字',
        icon: 'none',
      })
      this.setData({
        'addEdit.activity_price': e.detail.value.substring(0, e.detail.value.length - 1)
      })
      return
    }
  },

  //市场价
  marketPrice(e) {
    if (/^(\d?)+(\.\d{0,2})?$/.test(e.detail.value)) {
      this.setData({
        'addEdit.market_price': e.detail.value
      })
    } else {
      wx.showToast({
        title: '市场价请填写数字',
        icon: 'none',
      })
      this.setData({
        'addEdit.market_price': e.detail.value.substring(0, e.detail.value.length - 1)
      })
      return
    }
  },
  //拍卖底价
  bid_priceBtn(e) {
    this.setData({
      'addEdit.bid_price': e.detail.value
    })
  },
  //成交价
  bid_sold_priceBtn(e) {
    this.setData({
      'addEdit.bid_sold_price': e.detail.value
    })
  },
  //成交者手机号
  bid_phoneBtn(e) {
    this.setData({
      'addEdit.bid_phone': e.detail.value
    })
  },
  //保留价
  keep_priceBtn(e) {
    this.setData({
      'addEdit.keep_price': e.detail.value
    })
  },
  //流拍价
  unsold_priceBtn(e) {
    this.setData({
      'addEdit.unsold_price': e.detail.value
    })
  },
  //拍卖类型
  bid_radio(e){
    var num = e.detail.value
    var that = this
    that.data.addEdit.is_bid_sold
    if (num == 1){
      that.setData({
        bid_radio_type:num,
        'addEdit.is_bid_sold': 1,
        'addEdit.is_keep': 0,
        'addEdit.keep_price': '',
        'addEdit.is_unsold': 0,
        'addEdit.unsold_price': '',
      })
    }
    if (num == 2) {
      that.setData({
        bid_radio_type: num,
        'addEdit.is_bid_sold': 0,
        'addEdit.bid_sold_price': '',
        'addEdit.bid_phone': '',
        'addEdit.is_keep': 1,
        'addEdit.is_unsold': 0,
        'addEdit.unsold_price': '',
      })
    }
    if (num == 3) {
      that.setData({
        bid_radio_type: num,
        'addEdit.is_bid_sold': 0,
        'addEdit.bid_sold_price': '',
        'addEdit.bid_phone': '',
        'addEdit.is_keep': 0,
        'addEdit.keep_price': '',
        'addEdit.is_unsold': 1,
      })
    }
  },
  //商品保养情况
  maintenanceSelected(e) {
    var id;
    if (e.detail.value == "仅清洗"){
      id = 0
    }
    if (e.detail.value == "已护理"){
      id = 1
    }
    if (e.detail.value == "未护理"){
      id = 2
    }
    this.setData({
      'addEdit.maintenance': id
    })
  },
  //适用人群
  groupPeople(e) {
    this.setData({
      'addEdit.group_people': e.detail.value
    })
  },
  //机芯类型
  mechanism_btn(e) {
    this.setData({
      'addEdit.mechanism': e.detail.value
    })
  },
  //添加颜色
  add_color(e){
    this.setData({
      "addEdit.color":e.detail.value
    })
  },
  //弹框
  commQuality(e) {
    console.log('e', e)
    let show = e.currentTarget.dataset.type;
    if (show == '0') {
      this.setData({
        showCommQuality: true,
      })
    } else if (show == '1') {
      this.setData({
        showLibraryAge: true,
      })
    } else if (show == '2') {
      this.setData({
        showTradePrice: true,
      })
    }

  },
  // 关闭弹框
  closed() {
    this.setData({
      showCommQuality: false,
      showLibraryAge: false,
      showTradePrice: false,
    })
  },
  // 页面显示
  onShow: function() {
    var pages = getCurrentPages();
    console.log('onshow')
  },
  // 包装清单输入
  product_inp(e) {
    this.setData({
      product_inp: e.detail.value
    })
  },
  //表壳材质
  biaoke_inp(e) {
    this.setData({
      biaoke_inp: e.detail.value
    })
  },
  //保存
  save(e) {
    console.log(this.data.addEdit.product_condition)
    var _this = this;
    var qingdan = []
    var biaoke = []
    var biaodai = []
    var lis_line = _this.data.detailedList
    var biaolis = _this.data.CaseMaterial
    var biaodai_lis = _this.data.BandMaterial
    for (var i = 0; i < lis_line.length; i++) {
      if (lis_line[i].state == 1) {
        qingdan.push(lis_line[i].name)
      }
    }
    for (var j = 0; j < biaolis.length; j++) {
      if (biaolis[j].state == 1) {
        biaoke.push(biaolis[j].name)
      }
    }
    for (var k = 0; k < biaodai_lis.length; k++) {
      if (biaodai_lis[k].state == 1) {
        biaodai.push(biaodai_lis[k].name)
      }
    }
    if (_this.data.product_inp != '') {
      qingdan.push(_this.data.product_inp)
    }
    if (_this.data.biaoke_inp != '') {
      biaoke.push(_this.data.biaoke_inp)
    }
    if (_this.data.BandMaterial_inp != '') {
      biaodai.push(_this.data.BandMaterial_inp)
    }
    _this.data.addEdit.product_package = qingdan
    _this.data.addEdit.watchshell_material = biaoke
    _this.data.addEdit.watchband_material = biaodai
    if (_this.data.addEdit.image.length == 0) {
      wx.showToast({
        title: '请上传图片',
        icon: 'none',
        mask: true
      })
      return
    }
    addProduct({ ...this.data.addEdit,
      token: app.globalData.token
    }).then(res => {
      console.log('保存', res)
      if (res.data.code == 666) {
        wx.showToast({
          title: '添加成功',
          icon: 'none',
          mask: true,
          success: function(res) {
            var pages = getCurrentPages();
            var currPage = pages[pages.length - 1]; //当前页面
            var prevPage = pages[pages.length - 2]; //上一个页面
            var productItems = 'productItems[' + _this.data.pIndex + ']';
            //直接调用上一个页面的setData()方法，把数据存到上一个页面中去
            prevPage.setData({
              [productItems]: _this.data.addEdit
            })
            if (e.currentTarget.dataset.id == 0) {
              wx.setStorageSync('controlType', 'goodControl');
              wx.setStorageSync('del-add-data', 'add')
              wx.switchTab({
                url: '../goodControl/goodControl'
              })
            } else {
              wx.redirectTo({
                url: '/pages/addGood/addGood',
              })
            }
          },
        })
      } else if (res.data.code == 111111) {
        wx.showToast({
          title: '登录失效，请重新登录',
          icon: 'none',
        })
        setTimeout(function() {
          wx.reLaunch({
            url: '/pages/user/login/login',
          })
        }, 1500)
      } else {
        console.log(res.data.msg)
        wx.showToast({
          title: res.data.msg,
          icon: 'none',
          mask: true,
        })
      }
    })

  },
  //编辑操作
  //删除商品
  delete() {
    var _this = this;
    if (_this.data.addEdit.is_bid_sold == 1){
      wx.showToast({
        title: '该商品已售不能删除',
        icon:'none'
      })
      return
    }
    wx.showModal({
      title: '删除',
      content: '是否确认删除',
      confirmColor: '#000',
      success: function(e) {
        console.log(e)
        if (e.confirm) {
          delGoods({
            token: app.globalData.token,
            id: _this.data.addEdit.id
          }).then(res => {
            if (res.data.code == 666) {
              wx.showToast({
                title: '删除成功',
              })
              wx.setStorageSync('controlType', 'goodControl');
              wx.setStorageSync('del-add-data', 'del')
              setTimeout(function() {
                wx.switchTab({
                  url: '../goodControl/goodControl',
                })
              }, 1500)

            } else if (res.data.code == 111111) {
              wx.showToast({
                title: '登录失效，请重新登录',
                icon: 'none',
              })
              setTimeout(function() {
                wx.reLaunch({
                  url: '/pages/user/login/login',
                })
              }, 1500)
            } else {
              wx.showToast({
                title: res.data.msg,
                icon: 'none',
                mask: true
              })
            }
          })
        }
      }
    })

  },
  //保存编辑
  saveEdit() {
    var _this = this;
    var qingdan = []
    var biaoke = []
    var biaodai = []
    var lis_line = _this.data.detailedList
    var biaolis = _this.data.CaseMaterial
    var biaodai_lis = _this.data.BandMaterial
    

    for (var i = 0; i < lis_line.length; i++) {
      if (lis_line[i].state == 1) {
        if (lis_line[i].id) {
          qingdan.push({
            package_name: lis_line[i].name,
            id: lis_line[i].id
          })
        } else {
          qingdan.push({
            package_name: lis_line[i].name,
            id: ''
          })
        }
      }
    }
    _this.data.addEdit.product_package = qingdan
    for (var j = 0; j < biaolis.length; j++) {
      if (biaolis[j].state == 1) {
        if (biaolis[j].id) {
          biaoke.push({
            watchshell_material: biaolis[j].name,
            id: biaolis[j].id
          })
        } else {
          biaoke.push({
            watchshell_material: biaolis[j].name,
            id: ''
          })
        }
      }
    }
    _this.data.addEdit.watchshell_material = biaoke
    for (var k = 0; k < biaodai_lis.length; k++) {
      if (biaodai_lis[k].state == 1) {
        if (biaodai_lis[k].id) {
          biaodai.push({
            watchband_material: biaodai_lis[k].name,
            id: biaodai_lis[k].id
          })
        } else {
          biaodai.push({
            watchband_material: biaodai_lis[k].name,
            id: ''
          })
        }
      }
    }
    _this.data.addEdit.watchband_material = biaodai
    _this.data.addEdit.stock = 1
    if (_this.data.addEdit.image.length == 0) {
      wx.showToast({
        title: '请上传图片',
        icon: 'none',
        mask: true
      })
      return
    }
  
    let addEdit = this.data.addEdit;
    var _this = this;
    addEdit.token = app.globalData.token;
    console.log(_this.data.addEdit.id)
    var imgs = this.data.addEdit.image
    console.log(this.data.addEdit)
    
    saveEdit(addEdit).then(res => {
      if (res.data.code == 666) {
        var pages = getCurrentPages();
        var currPage = pages[pages.length - 1]; //当前页面
        var prevPage = pages[pages.length - 2]; //上一个页面
        var productItems = 'productItems[' + _this.data.pIndex + ']';
        //直接调用上一个页面的setData()方法，把数据存到上一个页面中去
        prevPage.setData({
          [productItems]: _this.data.addEdit
        })
        wx.setStorageSync('controlType', 'goodControl');
        wx.switchTab({
          url: '../goodControl/goodControl',
        })
      } else if (res.data.code == 111111) {
        wx.showToast({
          title: '登录失效，请重新登录',
          icon: 'none',
        })
        setTimeout(function() {
          wx.reLaunch({
            url: '/pages/user/login/login',
          })
        }, 1500)
      } else {
        console.log(res)
        wx.showToast({
          title: res.data.msg,
          icon: 'none',
          mask: true,
        })
      }
    })
  },
  onUnload() {
    wx.setStorageSync('controlType', 'goodControl');
    console.log(wx.getStorageSync('del-add-data'))
  },

  // 包装清单
  detailedBtn(e) {
    var index = e.currentTarget.dataset.index;
    var that = this
    if (that.data.detailedList[index].state === 0) {
      that.data.detailedList[index].state = 1
    } else {
      that.data.detailedList[index].state = 0
    }
    that.setData({
      detailedList: that.data.detailedList,
    })
  },
  //表壳材质
  CaseMaterialBtn(e) {
    var index = e.currentTarget.dataset.index;
    var that = this
    if (that.data.CaseMaterial[index].state == 0) {
      that.data.CaseMaterial[index].state = 1
    } else {
      that.data.CaseMaterial[index].state = 0
    }
    that.setData({
      CaseMaterial: that.data.CaseMaterial
    })
  },
  //表带材质
  BandMaterial(e) {
    var index = e.currentTarget.dataset.index;
    var that = this
    if (that.data.BandMaterial[index].state == 0) {
      that.data.BandMaterial[index].state = 1
    } else {
      that.data.BandMaterial[index].state = 0
    }
    that.setData({
      BandMaterial: that.data.BandMaterial
    })
  },
  //图片删除
  img_delete(e) {
    var index = e.currentTarget.dataset.index
    var node = this.data.showImages
    this.data.addEdit.image.splice(index, 1)
    node.splice(index, 1)
    console.log(this.data.addEdit)
    console.log(node)
    var that = this
    var that_count = 0
    console.log(that.data.showImages.length)
    if (15 - that.data.showImages.length > 9) {
      that_count = 9
    } else {
      that_count = 15 - that.data.showImages.length
    }
    this.setData({
      showImages: this.data.showImages,
      count: that_count
    })
  },
  //图片查看
  img_look(e) {
    var that = this
    var index = e.currentTarget.dataset.index
    wx.previewImage({
      current: that.data.showImages[index], // 当前显示图片的http链接
      urls: that.data.showImages // 需要预览的图片http链接列表
    })
  },

  //材质录入
  material_inp(e) {
    this.setData({
      'addEdit.material': e.detail.value
    })
  },
  //成色描述
  fineness_description(e) {
    var int = e.detail.value
    this.setData({
      'addEdit.fineness_description': int
    })
  },
 
  //小编推荐
  fineness_synopsis(e) {
    this.setData({
      'addEdit.synopsis': e.detail.value
    })
  },

  zhuanhChange(e){
    var num = e.detail.value
    var that = this    
    this.setData({
      currency_index: e.detail.value,
      'addEdit.peer_price_amount': that.data.addEdit.peer_price * that.data.currencyList[e.detail.value].value,
      'addEdit.peer_price_currency': that.data.currencyList[e.detail.value].name
    })
  }
})